-- Copyright (C) 2013 wgm.china (王光�?
--vss.utils is not OK

local type    = type
local pairs   = pairs
local ngx     = ngx
local string  = string
local table	  = table
local io	  = io
local tostring= tostring
local os      = os
local io_type = io.type

------new
local tb_concat    = table.concat
local tb_remove    = table.remove
local tb_insert    = table.insert

-------1定义公共组件(开�?---------------
local cjson = require("cjson")  								--加载json组件
local config_table = ngx.shared.gcs_config  					--定义gcs_config缓存

-------1定义公共组件（结束）----------------
module(...)
local VERSION = '0.1'

-------2加载配置文件（开始）----------------
local logfile = config_table:get("p_logfile") or "/image_root/gcs.log"	--log文件路径配置

-------2加载配置文件（结束）----------------
local file,err = io.open(logfile,"a")

-------fun save log(开�?---------------------
function gcs_log(info,text)
  --if loglevel = not then exit
  local loglevel = config_table:get("p_loglevel") or "debug" 					--log级别配置,debug,error,info,not
  if loglevel == "not" then
    return nil
  end
  local infonum = 0
  local loglevelnum = 0
  if info == "debug" then
    infonum = 5
  elseif info == "info" then
    infonum = 3
  elseif info == "error" then
    infonum = 1
  end
  if loglevel == "debug"  then
    loglevelnum = 5
  elseif loglevel == "info" then
    loglevelnum = 3
  elseif loglevel == "error" then
    loglevelnum = 1
  end

  if infonum <= loglevelnum then
    local isfile = io_type(file)
    if isfile == "closed file" then
      file,err = io.open(logfile,"a")
      ngx.log(ngx.ERR,"log file is not:"..io_type(file))
    end
    local timenum = ngx.now()
    local timestr = tostring(timenum)
    timestr = string.sub(timestr,11)--取ms
    timestr = "["..os.date("%Y-%m-%d %H:%M:%S",timenum)..timestr.."]"
    file:write(timestr..":["..info.."]:"..text)
    file:write("\r\n")
    file:flush()

  end

end
-------fun save log(结束)---------------------

-------fun return error信息(?���?-------------
--传入id，返回json(error_code:"",error_msg:"")
--根据错误ID返回信息
function return_error(id)
  local error_table = ngx.shared.gcs_error   --声明shared.error_table，用来取error_code,error_msg
  local error_code,error_msg
  local error_json = {}
  error_code = id
  error_json["error_code"] = error_code
  error_json["error_msg"] = error_table:get(error_code)
  local res = cjson.encode(error_json)
  gcs_log("error","return_error:"..res )
  return res
end
-------fun return error信息(结束)-------------

-------fun my_get_filename 取文件名�?开�?-------------
function my_get_filename(res)
  if  res then
    local filename = ngx.re.match(res,'(.+)filename="(.+)"(.*)')
    if filename then
      return filename[2]
    end
  else
    return nil
  end
end
-------fun my_get_filename 取文件名�?结束)-------------

-------fun get_type 取文件后缀�?开�?-------------
----根据文件名全称，返回后缀�?
function get_type(filename)
  if filename then
    local i =string.find(filename,"%.")
    local j =string.len(filename)
    if not i or not j then
      return nil
    end
    local filetype = string.sub(filename,i,j)
    return filetype
  else
    return nil
  end
end
-------fun get_type 取文件后缀�?结束)-------------
-------fun string.split 根据string按分隔符转换成数�?开�?-------------
string.split = function(s, p)
  local rt= {}
  string.gsub(s, '[^'..p..']+', function(w) table.insert(rt,w) end )
  return rt
end
-------fun string.split 根据string按分隔符转换成数�?结束)-------------
-------fun get_filename根据路径以及文件名，返回路径以及文件名称(开�?---------
function get_filename(filename)
  local file = string.gsub(filename,"\\","/")
  local tb = string.split(file,"/")
  local i = table.maxn(tb)
  local fname = tb[i]
  if i == 1 then
    return "",fname
  else

    local k = string.len(fname)+ 1
    local fpath = string.sub(file,1,-k)
    return fpath,fname
  end

end
-------fun get_filename根据路径以及文件名，返回路径以及文件名称(开�?---------
--
function html2str(html)
  local gsub = string.gsub
  local str = gsub(gsub(gsub(gsub(gsub(html,"&nbsp;"," "),"&gt;",">"),"&lt;","<"),"&amp;","&"),"&quot;",'"')
  return str
end


function str2html(str)
  local gsub = string.gsub
  local html = gsub(gsub(gsub(gsub(gsub(str," ","&nbsp;"),">","&gt;"),"<","&lt;"),"&","&amp;"),'"',"&quot;")
  return html
end

---通过table.concat来连接字符串，并可以通过sign来连接符的
function fun_concat_data (sign,...)
  local tb_arg = {...}
  if sign == '' then
    return tb_concat(tb_arg)
  else 
    local tb_res = {}
    for i,v in pairs(tb_arg) do
      if i ~= "n" then
        tb_insert(tb_res,v)
        tb_insert(tb_res,sign)
      end
    end
    tb_remove(tb_res,#tb_res)
    return tb_concat(tb_res)
  end
end

---check_parameter() 是用来检测表中key是否存在
---tb_parameter 是一个table  {id='',num='',..}
--parametes 是一个table  {'id','num',..}
function check_parameter(tb_parameter,parametes)

  if type(tb_parameter) ~= 'table' or type(parametes) ~= 'table' then
    return nil,"Parameter must be table format",1600
  end
  for _,v in pairs(parametes) do
    if not tb_parameter[v] then
      return nil,v .. " is nil",1600
    end
  end
  return tb_parameter,nil,nil
end





